﻿using System.Collections.Specialized;
using System.Web.Routing;
using System.Web.UI;

namespace Basmus.Values.Web
{
    public static class WebLinkServiceExtensions
    {
        public static string GetUrl<TModel>(this WebLinkService webLinkService, SchemeKey schemeKey, TModel model)
        {
            var url = webLinkService.GetUrl(typeof (TModel), schemeKey, model);
            return url;
        }
        public static string GetUrl<TModel>(this WebLinkService webLinkService, TModel model)
        {
            var url = webLinkService.GetUrl(typeof (TModel), model);
            return url;
        }

        public static void SetModel<TModel>(this  WebLinkService webLinkService, TModel model, Page page)
        {
            var valueProvider = GetValueProvider(page.RouteData, page.Request.QueryString, true);
            var schemeKey = RoutingHelper.GetRouteKey(page.RouteData);
            webLinkService.SetModel(typeof(TModel), schemeKey, model, valueProvider);
        }

        public static TModel CreateModel<TModel>(this  WebLinkService webLinkService, Page page)
            where TModel : new()
        {
            var requestModel = new TModel();
            webLinkService.SetModel(requestModel, page);
            return requestModel;
        }

        public static IValuesProvider<string > GetValueProvider(this Page page, bool merge)
        {
            var valueProvider = new CompositeValuesProvider<string>(new IValuesProvider<string>[]
                                                               {
                                                                   new RouteDataValuesProvider(page.RouteData),
                                                                   new NameStringValuesCollectionValuesProvider(
                                                                       page.Request.QueryString)
                                                               }, merge);
            return valueProvider;
        }


        public static IValuesProvider<string> GetValueProvider(RouteData getPageRouteData, NameValueCollection getPageQueryString, bool merge)
        {
            var valueProvider = new CompositeValuesProvider<string>(new IValuesProvider<string>[]
                                                               {
                                                                   new RouteDataValuesProvider(getPageRouteData),
                                                                   new NameStringValuesCollectionValuesProvider(
                                                                       getPageQueryString)
                                                               }, merge);
            return valueProvider;
        }
    }
}
